package com.loveto.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.loveto.common.JsonUtils;
import com.loveto.common.SoftKeyboardDetectorView;
import com.loveto.common.SoftKeyboardDetectorView.OnHiddenKeyboardListener;
import com.loveto.common.SoftKeyboardDetectorView.OnShownKeyboardListener;
import com.loveto.constant.LovetoConstant;

public class OpenTournamentMainActivity extends BaseActivity implements
View.OnClickListener{
	
	// 사용하는 변수들
	private Intent intentMoveToPage;
	private int presentInputRound;
	private String tournamentTitle;
	private SharedPreferences prefTournament;
	private Editor editor;
	private List<String> timeListForDB;
	private Spinner timeSpinner;
	private Handler myHandler = new Handler();
	private ProgressDialog progressDialog;
	private String memberid = "";
	private boolean isShowKeyboard;
	private SoftKeyboardDetectorView softKeyboardDetector; 
	private EditText editTextTitle;
	private String suspend_date;
	private String suspend_reason;
	private boolean isSaveSuccess;
	private String errorMsg;
	private String phone_uid;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_open_tournament_main);

		//변수 선언
		progressDialog = new ProgressDialog(this);
		prefTournament = getSharedPreferences("tournamentMakeInfo", Activity.MODE_PRIVATE);
		editor = prefTournament.edit();
		timeListForDB = new ArrayList<String>(); //DB 에 넣을 시간값 리스트
		timeSpinner = (Spinner) findViewById(R.id.spinnerDeadline);
		SharedPreferences prefUser = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = prefUser.getString("memberid", "");
		phone_uid = prefUser.getString("phone_uid", "");
		editTextTitle = (EditText) findViewById(R.id.edit_title);
		isSaveSuccess = false;
		
		// 클릭 리스너 달기
		RelativeLayout round1_area = (RelativeLayout) findViewById(R.id.round1_area);
		round1_area.setOnClickListener(this);
		RelativeLayout round2_area = (RelativeLayout) findViewById(R.id.round2_area);
		round2_area.setOnClickListener(this);
		RelativeLayout round3_area = (RelativeLayout) findViewById(R.id.round3_area);
		round3_area.setOnClickListener(this);
		ImageView btn_open_tournament = (ImageView) findViewById(R.id.btn_open_new_tournament);
		btn_open_tournament.setOnClickListener(this);
		RelativeLayout btnGogoBack = (RelativeLayout) findViewById(R.id.btn_goto_back);
		btnGogoBack.setOnClickListener(this);
		
		//제목,질문입력을 보여줌. 쉐어드프리퍼런스에서 잃어옴.
		setQuestion();
		//스피너에 시간 넣어주기
		setDeadlineTime();
		
		//키보드가 나왔는지 학인 처리 , AndroidManifest.xml에서 android:windowSoftInputMode 가 adjustResize 속성일 때만 가능.
		isShowKeyboard = false; //키보드 상태를 파악하기 위한
		softKeyboardDetector = new  SoftKeyboardDetectorView(this); //키보드가 나왔는지 확인하기 위한
		addContentView(softKeyboardDetector, new FrameLayout.LayoutParams(-1, -1));
		softKeyboardDetector.setOnShownKeyboard(new OnShownKeyboardListener() {
			@Override
			public void onShowSoftKeyboard() {
				isShowKeyboard = true;
				editTextTitle.setCursorVisible(true);
				Log.d("tag", "키보드가 떴습니당~");
				Log.d("tag", "isShowKeyboard :" + isShowKeyboard);
			}
		});
		softKeyboardDetector.setOnHiddenKeyboard(new OnHiddenKeyboardListener() {
			
			@Override
			public void onHiddenSoftKeyboard() {
	        	reActiveButtons(); //다시 다른 버튼들 활성화
				editTextTitle.setCursorVisible(false);
				Log.d("tag", "키보드가 내려갔습니당~");
			}
		});
		
		//제목 입력란에 포커스 갈 때 처리
		final EditText editTitle = (EditText) findViewById(R.id.edit_title);
		editTitle.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				//포커스 갈 때 처리
				if ( hasFocus == true ) {
					editTitle.setTextColor(R.color.textDarkBlack);
				}
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		//현재 적힌 제목을 가져옴.
		EditText vTournamentTitle = (EditText) findViewById(R.id.edit_title);
		tournamentTitle = vTournamentTitle.getText().toString();
		switch (v.getId()) {
		case R.id.round1_area:
			if (!isShowKeyboard) {
				intentMoveToPage = new Intent(OpenTournamentMainActivity.this,OpenTournamentQuestionActivity.class);
				if (!("".equals(tournamentTitle))) {
					editor.putString("tournamentTitleText", tournamentTitle);
					editor.commit();
				}
				presentInputRound = 1;
				intentMoveToPage.putExtra("presentInputRound", presentInputRound);
				startActivity(intentMoveToPage);
			}
			break;
		case R.id.round2_area:
			if (!isShowKeyboard) {
				intentMoveToPage = new Intent(OpenTournamentMainActivity.this,OpenTournamentQuestionActivity.class);
				if (!("".equals(tournamentTitle))) {
					editor.putString("tournamentTitleText", tournamentTitle);
					editor.commit();
				}
				presentInputRound = 2;
				intentMoveToPage.putExtra("presentInputRound", presentInputRound);
				startActivity(intentMoveToPage);
			}
			break;
		case R.id.round3_area:
			if (!isShowKeyboard) {
				intentMoveToPage = new Intent(OpenTournamentMainActivity.this,OpenTournamentQuestionActivity.class);
				if (!("".equals(tournamentTitle))) {
					editor.putString("tournamentTitleText", tournamentTitle);
					editor.commit();
				}
				presentInputRound = 3;
				intentMoveToPage.putExtra("presentInputRound", presentInputRound);
				startActivity(intentMoveToPage);
			}
			break;
		case R.id.btn_open_new_tournament:
			if (isNetworkAvailableAndNotice()){
				if (!isShowKeyboard) {
					saveTournamentOpenInfoToServer();
				}
			}
			break;
		case R.id.btn_goto_back:
			finish();
			break;
		}
	}
	
	//화면 아무곳이나 클릭 했을 때 처리 (키보드 나왔을 때 처리 위한)
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
	    switch (ev.getAction()){
	        case MotionEvent.ACTION_DOWN:
	        	if (isShowKeyboard) {
		        	InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		        	mgr.hideSoftInputFromWindow(editTextTitle.getWindowToken(), 0);
	        	}
	            break;
	        case MotionEvent.ACTION_UP:
	            break;
	    }
	    return super.dispatchTouchEvent(ev);
	}
	
	private void saveTournamentOpenInfoToServer() {
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//제목 받아오기
				String title = prefTournament.getString("tournamentTitleText", "");
				//마감 시간(스트링) 받아오기
				int spinnerSelectedNum = timeSpinner.getSelectedItemPosition();
				String answerEndtime = timeListForDB.get(spinnerSelectedNum);
				//질문 받아오기
				String oneRoundQuestion = prefTournament.getString("questionTextRound01", "");
				String twoRoundQuestion = prefTournament.getString("questionTextRound02", "");
				String threeRoundQuestion = prefTournament.getString("questionTextRound03", "");
				//카테고리 받아오기
				String oneRoundQuestionCategory = prefTournament.getString("lowCategoryNameRound01", "");
				String twoRoundQuestionCategory = prefTournament.getString("lowCategoryNameRound02", "");
				String threeRoundQuestionCategory = prefTournament.getString("lowCategoryNameRound03", "");
				Log.d("tag", "입력 완료!");
				if ("".equals(title)) {
					myAlert("제목을 입력하세요!");
				} else if ("".equals(oneRoundQuestionCategory)) {
					myAlert("1ROUND 질문을 입력하세요!");
				} else if ("".equals(twoRoundQuestionCategory)) {
					myAlert("2ROUND 질문을 입력하세요!");
				} else if ("".equals(threeRoundQuestionCategory)) {
					myAlert("3ROUND 질문을 입력하세요!");
				} else { //모두 입력 완료 시
					progressDialog.setMessage("정보를 서버에 저장하고 있습니다.");
					progressDialog.show();
					Log.d("tag", "openTournament start");
					try {
						//서버에 정보 보내기
						StringBuffer url = new StringBuffer(LovetoConstant.OPEN_TOURNAMENT_URL);
						url.append("?memberid=").append(memberid).append("&title=").append(URLEncoder.encode(title,"UTF-8")).append("&answerEndtime=").append(answerEndtime);
						url.append("&oneRoundQuestion=").append(URLEncoder.encode(oneRoundQuestion,"UTF-8")).append("&twoRoundQuestion=").append(URLEncoder.encode(twoRoundQuestion,"UTF-8")).append("&threeRoundQuestion=").append(URLEncoder.encode(threeRoundQuestion,"UTF-8"));
						url.append("&oneRoundQuestionCategory=").append(URLEncoder.encode(oneRoundQuestionCategory,"UTF-8")).append("&twoRoundQuestionCategory=").append(URLEncoder.encode(twoRoundQuestionCategory,"UTF-8")).append("&threeRoundQuestionCategory=").append(URLEncoder.encode(threeRoundQuestionCategory,"UTF-8"));
						url.append("&phone_uid=").append(phone_uid);
						Log.d("tag", "url : " + url.toString());
						String jsonText = JsonUtils.getStringFromUrl(url.toString());
						Log.d("tag", "jsonText : " + jsonText);
						//JSONArray jsonArray = new JSONArray(jsonText);
						JSONObject object = new JSONObject(jsonText);
						String result = object.getString("result");
						String err = object.getString("err");
						suspend_date = object.getString("suspend_date");
						suspend_reason = object.getString("suspend_reason");
						Log.d("tag", "result : " + result);
						Log.d("tag", "err : " + err);
						if (!"F".equals(result)) {
							isSaveSuccess = true;
						} else {
							errorMsg = err;
						}
					} catch (JSONException e) {
						e.printStackTrace();
						Log.d("tag", "setRoundInfo() error, " + e.getMessage());
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
						Log.d("tag", "setRoundInfo() error, " + e.getMessage());
					} finally {
						if (isSaveSuccess) {
							showSimpleAlertAndMoveActive("토너먼트가 주최 되었습니다.", OpenTournamentMainActivity.this, JoinedTournamentListActivity.class);
						} else if ("Incorrect PhoneID".equals(errorMsg)){
							//폰 인증정보가 틀린 경우
							showAlertIncorrectPhoneID(OpenTournamentMainActivity.this);
						} else if ("SuspendedID".equals(errorMsg)) {
							//이용 정지 상태인 경우
							showAlertSuspendID(OpenTournamentMainActivity.this, suspend_date, suspend_reason);
						} else if ("Get Data Fail".equals(errorMsg)) {
							showSimpleAlert("데이터 전달에 오류가 있습니다. 다시 시도해주세요.");
						} else {
							showSimpleAlert("데이터 저장에 실패했습니다. 다시 시도해주세요.");
						}
					}
					progressDialog.dismiss();
					Log.d("tag", "saveTournamentOpenInfoToServer() end");
				}

			}
		};
		new Thread(runnable).start();
	}
	
	private void setQuestion() {
		// intent 에서 받아온 값에 따라 질문 입력 처리
		SharedPreferences pref = getSharedPreferences("tournamentMakeInfo", Activity.MODE_PRIVATE);
		String tournamentTitleText = pref.getString("tournamentTitleText", "");
		Log.d("tag","저장된 제목은:" + tournamentTitleText);
		String lowCategoryNameRound01 = pref.getString("lowCategoryNameRound01", "");
		String questionTextRound01 = pref.getString("questionTextRound01", "");
		String lowCategoryNameRound02 = pref.getString("lowCategoryNameRound02", "");
		String questionTextRound02 = pref.getString("questionTextRound02", "");
		String lowCategoryNameRound03 = pref.getString("lowCategoryNameRound03", "");
		String questionTextRound03 = pref.getString("questionTextRound03", "");
		
		if (!("".equals(tournamentTitleText))) {
			EditText editTournamentTitle = (EditText) findViewById(R.id.edit_title);
			editTournamentTitle.setText(tournamentTitleText);
			editTournamentTitle.setTextColor(R.color.textDarkBlack);
		}
		if (!("".equals(lowCategoryNameRound01))) {
			TextView vRoundCategory01 = (TextView) findViewById(R.id.round01_category);
			vRoundCategory01.setText("[" + lowCategoryNameRound01 + "]");
			TextView vRoundQuestion01 = (TextView) findViewById(R.id.round01_question);
			vRoundQuestion01.setText(questionTextRound01);
		}
		if (!("".equals(lowCategoryNameRound02))) {
			TextView vRoundCategory02 = (TextView) findViewById(R.id.round02_category);
			vRoundCategory02.setText("[" + lowCategoryNameRound02 + "]");
			TextView vRoundQuestion02 = (TextView) findViewById(R.id.round02_question);
			vRoundQuestion02.setText(questionTextRound02);
		}
		if (!("".equals(lowCategoryNameRound03))) {
			TextView vRoundCategory03 = (TextView) findViewById(R.id.round03_category);
			vRoundCategory03.setText("[" + lowCategoryNameRound03 + "]");
			TextView vRoundQuestion03 = (TextView) findViewById(R.id.round03_question);
			vRoundQuestion03.setText(questionTextRound03);
		}
	}
	
	private void setDeadlineTime() {
		//스피터와 관련 어레이, 어뎁더 세팅
		List<String> timeListForSpinner = new ArrayList<String>(); //스피너에 넣을 스트링 리스트
		ArrayAdapter<String> timeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,timeListForSpinner); //스피너 어댑터
		timeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		timeSpinner.setAdapter(timeAdapter);
		timeSpinner.setPrompt("참여마감시간을 선택하세요.");
		
		//현재 시간 구하기
		GregorianCalendar today = new GregorianCalendar ();
		int hour = today.get(today.HOUR_OF_DAY); //현재 시간
		Date todayDate = new Date();
		Log.d("tag","현지 시간은:" + todayDate);
		Date SelectDate = new Date();
		//오늘 시간
		String str = "";
		String dateStr = "";
		//당일
		for (int i=hour+5;i<(48+hour);i=i+3){ //5시간 뒤 부터 선택 가능. , 최대 48시간 이후까지 가능
			int h = i;
			String strDay = "오늘"; 
			if(i < 10) {  //첫날 10시 전
				str = "0";
			} else if (i < 24) { //첫날 10시 이후
				str = "";
			} else if (i < 34) { //둘째날(내일) 10시 이전
				str = "0";
				h = i - 24;
				strDay = "내일"; 
			} else if (i < 48) { //둘째날(내일) 10시 이후
				str = "";
				h = i - 24;
				strDay = "내일"; 
			} else if (i < 58) { //셋째날(모레) 10시 이전
				str = "0";
				h = i - 48;
				strDay = "모레"; 
			} else {			//셋째날(모레) 10시 이후
				str = "";
				h = i - 48;
				strDay = "모레"; 
			}
			timeListForSpinner.add(strDay + " " + str + h + ":00");
			SelectDate = new Date (todayDate.getTime()+(long)(1000 * 60 * 60 * (i-hour))); 
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH");
			dateStr = sdf.format(SelectDate) +"00";
			timeListForDB.add(dateStr);
			Log.d("tag","date:" + dateStr);
		}
		
		timeAdapter.notifyDataSetChanged(); //동적 생성 스피너에 반영하기
		timeSpinner.setSelection(6);  //디폴트 선택값을 7번째로
		
	}
	
	public void viewToast(int gravity, int xOffset, int yOffset, String message) {
		Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
		toast.setGravity(gravity, xOffset, yOffset);
		toast.show();
	}
	
	public void myAlert(String msg) {
        new AlertDialog.Builder(this)
        .setMessage(msg)
        .setNeutralButton("확인", null)
        .show();
	}
	
	//키보드 표시 유무를 false 로 만듬. 딜레이를 주지 않으면 클릭 처리가 바로 되버림.
	private void reActiveButtons() { 
		new Handler().postDelayed(new Runnable()
        {
            @Override
            public void run()
            {
            	isShowKeyboard = false;
            	Log.d("tag", "isShowKeyboard :" + isShowKeyboard);
            }
        }, 300);
	}

}
